/**
 * Mock 数据服务
 * 用于开发阶段模拟后端接口响应
 */

// 模拟延迟
const mockDelay = (ms = 800) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟响应格式
const mockResponse = (data, code = 200, message = 'success') => ({
  code,
  message,
  data
})

// 生成模拟ID
let mockId = 1000
const generateId = () => ++mockId

// 模拟用户数据
const mockUsers = [
  {
    id: 1,
    username: 'admin',
    realName: '张管理',
    role: 'admin',
    email: 'admin@recycling.com',
    phone: '13800000001',
    address: '北京市朝阳区管理大厦100号',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 2,
    username: 'station_manager1',
    realName: '李站长',
    role: 'station_manager',
    email: 'manager1@recycling.com',
    phone: '13800000002',
    address: '北京市海淀区中关村大街1号',
    status: 'active',
    createdAt: '2024-01-02T00:00:00Z'
  },
  {
    id: 3,
    username: 'station_manager2',
    realName: '王站长',
    role: 'station_manager',
    email: 'manager2@recycling.com',
    phone: '13800000003',
    address: '北京市朝阳区建国路88号',
    status: 'active',
    createdAt: '2024-01-03T00:00:00Z'
  },
  {
    id: 4,
    username: 'customer1',
    realName: '陈客户',
    role: 'customer',
    email: 'customer1@example.com',
    phone: '13800000004',
    address: '北京市西城区西单大街66号',
    status: 'active',
    createdAt: '2024-01-04T00:00:00Z'
  },
  {
    id: 5,
    username: 'customer2',
    realName: '刘客户',
    role: 'customer',
    email: 'customer2@example.com',
    phone: '13800000005',
    address: '北京市东城区王府井大街188号',
    status: 'active',
    createdAt: '2024-01-05T00:00:00Z'
  }
]

// 模拟站点数据
const mockStations = [
  {
    id: 1,
    name: '海淀回收站',
    address: '北京市海淀区中关村科技园区',
    latitude: 39.9889,
    longitude: 116.3058,
    contactPhone: '010-62345678',
    capacity: 2000,
    currentLoad: 800,
    managerId: 2,
    managerName: '李站长',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 2,
    name: '朝阳回收站',
    address: '北京市朝阳区CBD核心区',
    latitude: 39.9056,
    longitude: 116.4702,
    contactPhone: '010-65432109',
    capacity: 1500,
    currentLoad: 600,
    managerId: 3,
    managerName: '王站长',
    status: 'active',
    createdAt: '2024-01-02T00:00:00Z'
  },
  {
    id: 3,
    name: '西城回收站',
    address: '北京市西城区金融街',
    latitude: 39.9139,
    longitude: 116.3669,
    contactPhone: '010-66543210',
    capacity: 1800,
    currentLoad: 400,
    managerId: null,
    managerName: '',
    status: 'busy',
    createdAt: '2024-01-03T00:00:00Z'
  }
]

// 模拟回收物品数据
const mockItems = [
  {
    id: 1,
    name: '废纸',
    category: '纸类',
    unit: 'kg',
    pricePerUnit: 2.50,
    description: '包括报纸、杂志、书籍、办公用纸等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 2,
    name: '塑料瓶',
    category: '塑料',
    unit: '个',
    pricePerUnit: 0.30,
    description: 'PET塑料瓶，矿泉水瓶、饮料瓶等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 3,
    name: '铝罐',
    category: '金属',
    unit: '个',
    pricePerUnit: 0.50,
    description: '易拉罐、铝制饮料罐等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 4,
    name: '废铁',
    category: '金属',
    unit: 'kg',
    pricePerUnit: 3.20,
    description: '废旧金属制品、铁丝、钢筋等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 5,
    name: '玻璃瓶',
    category: '玻璃',
    unit: 'kg',
    pricePerUnit: 0.80,
    description: '各类玻璃瓶、玻璃器皿等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 6,
    name: '旧衣物',
    category: '纺织品',
    unit: 'kg',
    pricePerUnit: 1.00,
    description: '清洁的旧衣服、床单、被套等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 7,
    name: '废电池',
    category: '有害垃圾',
    unit: 'kg',
    pricePerUnit: 8.00,
    description: '废旧电池、充电电池等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  },
  {
    id: 8,
    name: '纸箱',
    category: '纸类',
    unit: 'kg',
    pricePerUnit: 2.00,
    description: '快递纸箱、包装纸箱等',
    status: 'active',
    createdAt: '2024-01-01T00:00:00Z'
  }
]

// 模拟订单数据
const mockOrders = [
  {
    id: 1,
    orderNo: 'RC202409230001',
    customerId: 4,
    customerName: '陈客户',
    customerPhone: '13800000004',
    stationId: 1,
    stationName: '海淀回收站',
    pickupAddress: '北京市西城区西单大街66号101室',
    pickupTime: '2024-09-24T10:00:00Z',
    actualPickupTime: '2024-09-24T10:15:00Z',
    totalAmount: 78.50,
    totalWeight: 28.50,
    status: 'completed',
    notes: '客户很满意服务',
    createdAt: '2024-09-23T08:00:00Z',
    items: [
      { itemId: 1, itemName: '废纸', quantity: 15.0, unitPrice: 2.50, subtotal: 37.50 },
      { itemId: 2, itemName: '塑料瓶', quantity: 50, unitPrice: 0.30, subtotal: 15.00 },
      { itemId: 3, itemName: '铝罐', quantity: 20, unitPrice: 0.50, subtotal: 10.00 },
      { itemId: 4, itemName: '废铁', quantity: 5.0, unitPrice: 3.20, subtotal: 16.00 }
    ]
  },
  {
    id: 2,
    orderNo: 'RC202409230002',
    customerId: 5,
    customerName: '刘客户',
    customerPhone: '13800000005',
    stationId: 2,
    stationName: '朝阳回收站',
    pickupAddress: '北京市东城区王府井大街188号2楼',
    pickupTime: '2024-09-24T14:00:00Z',
    actualPickupTime: null,
    totalAmount: 45.80,
    totalWeight: 18.20,
    status: 'confirmed',
    notes: '预约下午2点取货',
    createdAt: '2024-09-23T10:00:00Z',
    items: [
      { itemId: 1, itemName: '废纸', quantity: 10.0, unitPrice: 2.50, subtotal: 25.00 },
      { itemId: 5, itemName: '玻璃瓶', quantity: 8.2, unitPrice: 0.80, subtotal: 6.56 },
      { itemId: 6, itemName: '旧衣物', quantity: 4.2, unitPrice: 1.00, subtotal: 4.20 },
      { itemId: 8, itemName: '纸箱', quantity: 5.0, unitPrice: 2.00, subtotal: 10.00 }
    ]
  },
  {
    id: 3,
    orderNo: 'RC202409230003',
    customerId: 4,
    customerName: '陈客户',
    customerPhone: '13800000004',
    stationId: 1,
    stationName: '海淀回收站',
    pickupAddress: '北京市丰台区丰台路99号',
    pickupTime: '2024-09-25T09:00:00Z',
    actualPickupTime: null,
    totalAmount: 92.30,
    totalWeight: 35.60,
    status: 'pending',
    notes: '新订单，待确认',
    createdAt: '2024-09-23T12:00:00Z',
    items: [
      { itemId: 1, itemName: '废纸', quantity: 20.0, unitPrice: 2.50, subtotal: 50.00 },
      { itemId: 2, itemName: '塑料瓶', quantity: 60, unitPrice: 0.30, subtotal: 18.00 },
      { itemId: 4, itemName: '废铁', quantity: 7.6, unitPrice: 3.20, subtotal: 24.32 }
    ]
  }
]

/**
 * Mock API 服务
 */
export const mockAPI = {
  // 认证相关
  auth: {
    async login(credentials) {
      await mockDelay()
      
      const user = mockUsers.find(u => 
        u.username === credentials.username && 
        credentials.password === '123456'
      )
      
      if (user) {
        // 直接返回数据，不使用mockResponse包装
        // 因为axios拦截器会处理响应格式
        return {
          user,
          token: `mock-token-${Date.now()}`,
          expiresIn: 7200
        }
      } else {
        throw new Error('用户名或密码错误')
      }
    },

    async getCurrentUser() {
      await mockDelay(300)
      return mockResponse(mockUsers[0])
    },

    async logout() {
      await mockDelay(300)
      return mockResponse({})
    }
  },

  // 用户管理
  users: {
    async getUsers(params = {}) {
      await mockDelay()
      
      let result = [...mockUsers]
      
      // 角色过滤
      if (params.role) {
        result = result.filter(user => user.role === params.role)
      }
      
      // 状态过滤
      if (params.status) {
        result = result.filter(user => user.status === params.status)
      }
      
      // 关键词搜索
      if (params.keyword) {
        const keyword = params.keyword.toLowerCase()
        result = result.filter(user => 
          user.realName.toLowerCase().includes(keyword) ||
          user.username.toLowerCase().includes(keyword) ||
          user.phone.includes(keyword)
        )
      }
      
      // 分页
      const page = parseInt(params.page) || 1
      const pageSize = parseInt(params.pageSize) || 10
      const start = (page - 1) * pageSize
      const end = start + pageSize
      
      return mockResponse({
        list: result.slice(start, end),
        total: result.length,
        page,
        pageSize
      })
    },

    async getUserById(userId) {
      await mockDelay(300)
      const user = mockUsers.find(u => u.id === parseInt(userId))
      if (user) {
        return mockResponse(user)
      } else {
        throw new Error('用户不存在')
      }
    },

    async createUser(userData) {
      await mockDelay()
      const newUser = {
        id: generateId(),
        ...userData,
        status: 'active',
        createdAt: new Date().toISOString()
      }
      mockUsers.push(newUser)
      return mockResponse(newUser)
    },

    async updateUser(userId, userData) {
      await mockDelay()
      const index = mockUsers.findIndex(u => u.id === parseInt(userId))
      if (index !== -1) {
        mockUsers[index] = { ...mockUsers[index], ...userData }
        return mockResponse(mockUsers[index])
      } else {
        throw new Error('用户不存在')
      }
    }
  },

  // 站点管理
  stations: {
    async getStations(params = {}) {
      await mockDelay()
      
      let result = [...mockStations]
      
      // 状态过滤
      if (params.status) {
        result = result.filter(station => station.status === params.status)
      }
      
      // 关键词搜索
      if (params.keyword) {
        const keyword = params.keyword.toLowerCase()
        result = result.filter(station => 
          station.name.toLowerCase().includes(keyword) ||
          station.address.toLowerCase().includes(keyword)
        )
      }
      
      // 分页
      const page = parseInt(params.page) || 1
      const pageSize = parseInt(params.pageSize) || 10
      const start = (page - 1) * pageSize
      const end = start + pageSize
      
      return {
        list: result.slice(start, end),
        total: result.length,
        page,
        pageSize
      }
    },

    async getStationById(stationId) {
      await mockDelay(300)
      const station = mockStations.find(s => s.id === parseInt(stationId))
      if (station) {
        return station
      } else {
        throw new Error('站点不存在')
      }
    },

    async getAvailableStations() {
      await mockDelay(300)
      const available = mockStations.filter(station => station.status === 'active')
      return available
    },

    async createStation(stationData) {
      await mockDelay()
      const newStation = {
        id: generateId(),
        ...stationData,
        currentLoad: 0,
        status: 'active',
        createTime: new Date().toISOString().split('T')[0]
      }
      mockStations.push(newStation)
      return { success: true, data: newStation }
    },

    async updateStation(stationId, stationData) {
      await mockDelay()
      const index = mockStations.findIndex(s => s.id === parseInt(stationId))
      if (index !== -1) {
        mockStations[index] = { ...mockStations[index], ...stationData }
        return { success: true, data: mockStations[index] }
      } else {
        throw new Error('站点不存在')
      }
    },

    async deleteStation(stationId) {
      await mockDelay()
      const index = mockStations.findIndex(s => s.id === parseInt(stationId))
      if (index !== -1) {
        mockStations.splice(index, 1)
        return { success: true }
      } else {
        throw new Error('站点不存在')
      }
    },

    async batchDeleteStations(stationIds) {
      await mockDelay()
      stationIds.forEach(id => {
        const index = mockStations.findIndex(s => s.id === parseInt(id))
        if (index !== -1) {
          mockStations.splice(index, 1)
        }
      })
      return { success: true }
    },

    async updateStationStatus(stationId, status) {
      await mockDelay()
      const station = mockStations.find(s => s.id === parseInt(stationId))
      if (station) {
        station.status = status
        return { success: true }
      } else {
        throw new Error('站点不存在')
      }
    },

    async assignManager(stationId, managerId) {
      await mockDelay()
      const station = mockStations.find(s => s.id === parseInt(stationId))
      const manager = mockUsers.find(u => u.id === parseInt(managerId))
      if (station && manager) {
        station.managerId = managerId
        station.managerName = manager.realName
        return { success: true }
      } else {
        throw new Error('站点或管理员不存在')
      }
    },

    async unassignManager(stationId) {
      await mockDelay()
      const station = mockStations.find(s => s.id === parseInt(stationId))
      if (station) {
        station.managerId = null
        station.managerName = ''
        return { success: true }
      } else {
        throw new Error('站点不存在')
      }
    },

    async getStationInventory(/* stationId */) {
      await mockDelay(300)
      // 模拟库存数据
      const inventoryData = [
        { 
          id: 1, itemId: 1, itemName: '废纸', category: '纸类', unit: 'kg', 
          quantity: 150.5, minStock: 50, maxStock: 300, averagePrice: 2.50, 
          lastUpdated: '2024-09-25T10:30:00Z' 
        },
        { 
          id: 2, itemId: 2, itemName: '塑料瓶', category: '塑料', unit: '个', 
          quantity: 300, minStock: 100, maxStock: 500, averagePrice: 0.30, 
          lastUpdated: '2024-09-25T09:15:00Z' 
        },
        { 
          id: 3, itemId: 3, itemName: '铝罐', category: '金属', unit: '个', 
          quantity: 180, minStock: 80, maxStock: 400, averagePrice: 0.50, 
          lastUpdated: '2024-09-25T08:45:00Z' 
        },
        { 
          id: 4, itemId: 4, itemName: '废铁', category: '金属', unit: 'kg', 
          quantity: 80.2, minStock: 30, maxStock: 200, averagePrice: 3.20, 
          lastUpdated: '2024-09-24T16:20:00Z' 
        }
      ]
      return { list: inventoryData, total: inventoryData.length }
    },

    async updateStationInventory(/* stationId, inventoryData */) {
      await mockDelay(500)
      return { success: true }
    }
  },

  // 物品管理
  items: {
    async getItems(params = {}) {
      await mockDelay()
      
      let result = [...mockItems]
      
      // 分类过滤
      if (params.category) {
        result = result.filter(item => item.category === params.category)
      }
      
      // 状态过滤
      if (params.status) {
        result = result.filter(item => item.status === params.status)
      }
      
      // 关键词搜索
      if (params.keyword) {
        const keyword = params.keyword.toLowerCase()
        result = result.filter(item => 
          item.name.toLowerCase().includes(keyword) ||
          item.description.toLowerCase().includes(keyword)
        )
      }
      
      // 分页
      const page = parseInt(params.page) || 1
      const pageSize = parseInt(params.pageSize) || 10
      const start = (page - 1) * pageSize
      const end = start + pageSize
      
      return mockResponse({
        list: result.slice(start, end),
        total: result.length,
        page,
        pageSize
      })
    },

    async getItemById(itemId) {
      await mockDelay(300)
      const item = mockItems.find(i => i.id === parseInt(itemId))
      if (item) {
        return mockResponse(item)
      } else {
        throw new Error('物品不存在')
      }
    },

    async createItem(itemData) {
      await mockDelay()
      const newItem = {
        id: generateId(),
        ...itemData,
        status: 'active',
        createdAt: new Date().toISOString()
      }
      mockItems.push(newItem)
      return mockResponse(newItem)
    },

    async updateItem(itemId, itemData) {
      await mockDelay()
      const index = mockItems.findIndex(i => i.id === parseInt(itemId))
      if (index !== -1) {
        mockItems[index] = { ...mockItems[index], ...itemData }
        return mockResponse(mockItems[index])
      } else {
        throw new Error('物品不存在')
      }
    }
  },

  // 订单管理
  orders: {
    async getOrders(params = {}) {
      await mockDelay()
      
      let result = [...mockOrders]
      
      // 状态过滤
      if (params.status) {
        result = result.filter(order => order.status === params.status)
      }
      
      // 客户过滤
      if (params.customerId) {
        result = result.filter(order => order.customerId === parseInt(params.customerId))
      }
      
      // 站点过滤
      if (params.stationId) {
        result = result.filter(order => order.stationId === parseInt(params.stationId))
      }
      
      // 订单号搜索
      if (params.orderNo) {
        result = result.filter(order => order.orderNo.includes(params.orderNo))
      }
      
      // 分页
      const page = parseInt(params.page) || 1
      const pageSize = parseInt(params.pageSize) || 10
      const start = (page - 1) * pageSize
      const end = start + pageSize
      
      return {
        list: result.slice(start, end),
        total: result.length,
        page,
        pageSize
      }
    },

    async getStationOrders(stationId, params = {}) {
      await mockDelay()
      
      let result = mockOrders.filter(order => order.stationId === parseInt(stationId))
      
      // 状态过滤
      if (params.status) {
        result = result.filter(order => order.status === params.status)
      }
      
      // 分页
      const page = parseInt(params.page) || 1
      const pageSize = parseInt(params.pageSize) || 10
      const start = (page - 1) * pageSize
      const end = start + pageSize
      
      return {
        list: result.slice(start, end),
        total: result.length,
        page,
        pageSize
      }
    },

    async getOrderById(orderId) {
      await mockDelay(300)
      const order = mockOrders.find(o => o.id === parseInt(orderId))
      if (order) {
        return order
      } else {
        throw new Error('订单不存在')
      }
    },

    async confirmOrder(orderId, confirmData) {
      await mockDelay(500)
      const order = mockOrders.find(o => o.id === parseInt(orderId))
      if (order) {
        order.status = 'confirmed'
        order.actualPickupTime = confirmData.actualPickupTime
        return { success: true }
      }
      throw new Error('订单不存在')
    },

    async startProcessing(orderId /* , processData */) {
      await mockDelay(500)
      const order = mockOrders.find(o => o.id === parseInt(orderId))
      if (order) {
        order.status = 'in_progress'
        return { success: true }
      }
      throw new Error('订单不存在')
    },

    async completeOrder(orderId /* , completionData */) {
      await mockDelay(500)
      const order = mockOrders.find(o => o.id === parseInt(orderId))
      if (order) {
        order.status = 'completed'
        return { success: true }
      }
      throw new Error('订单不存在')
    },

    async cancelOrder(orderId /* , reason */) {
      await mockDelay(500)
      const order = mockOrders.find(o => o.id === parseInt(orderId))
      if (order) {
        order.status = 'cancelled'
        return { success: true }
      }
      throw new Error('订单不存在')
    },

    async getOrdersStats(/* params = {} */) {
      await mockDelay(300)
      return {
        pending: 5,
        confirmed: 8,
        processing: 3,
        completed: 24,
        cancelled: 2,
        todayRevenue: 1280.50
      }
    },

    async createOrder(orderData) {
      await mockDelay()
      
      // 计算总金额和总重量
      let totalAmount = 0
      let totalWeight = 0
      
      orderData.items.forEach(item => {
        const itemInfo = mockItems.find(i => i.id === item.itemId)
        if (itemInfo) {
          const subtotal = item.quantity * itemInfo.pricePerUnit
          totalAmount += subtotal
          totalWeight += item.quantity
        }
      })
      
      const newOrder = {
        id: generateId(),
        orderNo: `RC${Date.now()}`,
        customerId: 4, // 默认客户
        customerName: '陈客户',
        customerPhone: '13800000004',
        stationId: orderData.stationId || 1,
        stationName: '海淀回收站',
        ...orderData,
        totalAmount: Math.round(totalAmount * 100) / 100,
        totalWeight: Math.round(totalWeight * 100) / 100,
        status: 'pending',
        createdAt: new Date().toISOString(),
        items: orderData.items.map(item => {
          const itemInfo = mockItems.find(i => i.id === item.itemId)
          return {
            ...item,
            itemName: itemInfo?.name || '',
            unitPrice: itemInfo?.pricePerUnit || 0,
            subtotal: Math.round(item.quantity * (itemInfo?.pricePerUnit || 0) * 100) / 100
          }
        })
      }
      
      mockOrders.push(newOrder)
      return mockResponse(newOrder)
    },

    async calculateOrderPrice(items) {
      await mockDelay(300)
      
      let totalAmount = 0
      let totalWeight = 0
      const itemDetails = []
      
      items.forEach(item => {
        const itemInfo = mockItems.find(i => i.id === item.itemId)
        if (itemInfo) {
          const subtotal = item.quantity * itemInfo.pricePerUnit
          totalAmount += subtotal
          totalWeight += item.quantity
          
          itemDetails.push({
            itemId: item.itemId,
            itemName: itemInfo.name,
            quantity: item.quantity,
            unitPrice: itemInfo.pricePerUnit,
            subtotal: Math.round(subtotal * 100) / 100
          })
        }
      })
      
      return mockResponse({
        items: itemDetails,
        totalAmount: Math.round(totalAmount * 100) / 100,
        totalWeight: Math.round(totalWeight * 100) / 100
      })
    }
  },

  // 数据分析
  analytics: {
    async getDashboardOverview(/* params = {} */) {
      await mockDelay()
      
      return mockResponse({
        totalOrders: 156,
        totalRevenue: 12580.50,
        totalWeight: 4520.8,
        activeStations: 8,
        totalCustomers: 89,
        todayOrders: 12,
        todayRevenue: 850.30,
        recentOrders: mockOrders.slice(0, 5),
        orderStatusStats: {
          pending: 15,
          confirmed: 25,
          in_progress: 18,
          completed: 95,
          cancelled: 3
        },
        stationLoadStats: mockStations.map(station => ({
          name: station.name,
          loadPercentage: Math.round((station.currentLoad / station.capacity) * 100)
        }))
      })
    },

    async getOrderTrends(/* params = {} */) {
      await mockDelay()
      
      const dates = []
      const orders = []
      const revenue = []
      
      for (let i = 6; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        dates.push(date.toISOString().split('T')[0])
        orders.push(Math.floor(Math.random() * 20) + 10)
        revenue.push(Math.floor(Math.random() * 1000) + 500)
      }
      
      return mockResponse({
        dates,
        orders,
        revenue
      })
    }
  },

  // 系统设置
  settings: {
    async getSystemSettings() {
      await mockDelay()
      return mockResponse({
        systemName: '资源回收管理平台',
        version: '1.0.0',
        description: '智能化资源回收管理系统',
        maintenanceMode: false,
        allowRegistration: true
      })
    },

    async updateSystemSettings(/* settings */) {
      await mockDelay()
      return mockResponse({ success: true })
    },

    async getEmailSettings() {
      await mockDelay()
      return mockResponse({
        smtpHost: '',
        smtpPort: 587,
        encryption: 'tls',
        fromEmail: '',
        password: '',
        fromName: '资源回收平台',
        enabled: false
      })
    },

    async updateEmailSettings(/* settings */) {
      await mockDelay()
      return mockResponse({ success: true })
    },

    async testEmailSettings(/* settings */) {
      await mockDelay()
      return mockResponse({ success: true })
    }
  }
}

export default mockAPI
